package com.yy.utils.ntes;

import java.io.IOException;
import java.util.Date;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.yy.utils.PropertiesUtil;


/**
 * 网易视频云
 * 直播点播
 * @author yy 
 * @date 2017-04-06 14:39:47
 */
public class VodLive {
	/**
	 * 创建频道
	 */
	private static String createUrl="https://vcloud.163.com/app/channel/create";
	/**
	 * 修改频道
	 */
	private static String updateUrl="https://vcloud.163.com/app/channel/update";
	/**
	 * 删除频道
	 */
	private static String deleteUrl="https://vcloud.163.com/app/channel/delete";
	/**
	 * 获取频道状态
	 */
	private static String channelstatsUrl="https://vcloud.163.com/app/channelstats";
	/**
	 * 获取频道列表
	 */
	private static String channellistUrl="https://vcloud.163.com/app/channellist";
	/**
	 * 禁用频道
	 */
	private static String pauseUrl="https://vcloud.163.com/app/channel/pause";
	/**
	 * 恢复频道
	 */
	private static String resumeUrl="https://vcloud.163.com/app/channel/resume";
	/**
	 * 重新获取推流地址
	 */
	private static String addressUrl="https://vcloud.163.com/app/address";
	/**
	 * 重新获取推流地址
	 * @param cid 频道ID，32位字符串
	 * @return ret:data
	 * pushUrl	String	推流地址;httpPullUrl	String	http拉流地址;hlsPullUrl	String	hls拉流地址;rtmpPullUrl	String	rtmp拉流地址;
	 * code	int	状态;	 msg	String	错误信息;
	 */
	public static String address(String cid){
		HttpPost httpPost = vod(addressUrl);
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"cid\":\""+cid+"\"}",Consts.UTF_8);
        httpPost.setEntity(params);
		return responseData(httpPost,params);
	}
	/**
	 * 恢复频道
	 * @param cid 频道ID，32位字符串
	 * @return code	int	状态;	 msg	String	错误信息
	 */
	public static String resume(String cid){
		HttpPost httpPost = vod(resumeUrl);
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"cid\":\""+cid+"\"}",Consts.UTF_8);
        httpPost.setEntity(params);
		return responseData(httpPost,params);
	}
	/**
	 * 禁用频道
	 * @param cid 频道ID，32位字符串
	 * @return code	int	状态;	 msg	String	错误信息
	 */
	public static String pause(String cid){
		HttpPost httpPost = vod(pauseUrl);
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"cid\":\""+cid+"\"}",Consts.UTF_8);
        httpPost.setEntity(params);
		return responseData(httpPost,params);
	}
	/**
	 * 获取频道列表
	 * @param records 单页记录数，默认值为10	int
	 * @param pnum 要取第几页，默认值为1	int
	 * @param ofield 排序的域，支持的排序域为：ctime（默认）	String
	 * @param sort 升序还是降序，1升序，0降序，默认为desc	int
	 * @return ret:list[]
	 * ctime	Long	创建频道的时间戳;cid	String	频道ID，32位字符串;name	String	频道名称;
	 * status	int	频道状态（0：空闲； 1：直播； 2：禁用； 3：直播录制）;type	int	频道类型 ( 0 : rtmp, 1 : hls, 2 : http);
	 * uid	Long	用户ID;
	 * code	int	状态码;msg	String	错误信息;
	 */
	public static String channellist(int records){
		HttpPost httpPost = vod(channellistUrl);
		StringBuffer stringBuffer = new StringBuffer("{");
		stringBuffer.append("}");
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"records\":"+records+"}",Consts.UTF_8);
        httpPost.setEntity(params);
		return responseData(httpPost,params);
	}
	/**
	 * 获取频道状态
	 * @param cid 频道ID，32位字符串
	 * @return ret:data
	 * cid	String	频道ID，32位字符串;name	String	频道名称;status	int	频道状态（0：空闲； 1：直播； 2：禁用； 3：直播录制）;
	 * type	int	频道类型 ( 0 : rtmp, 1 : hls, 2 : http);uid	Long	用户ID;
	 * code	int	状态码;msg	String	错误信息
	 */
	public static String channelstats(String cid){
		HttpPost httpPost = vod(channelstatsUrl);
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"cid\":\""+cid+"\"}",Consts.UTF_8);
        httpPost.setEntity(params);
		return responseData(httpPost,params);
	}
	/**
	 * 删除频道
	 * @param cid 频道ID，32位字符串
	 * @return code	int	状态码;msg	String	错误信息
	 */
	public static String delectChannel(String cid){
		HttpPost httpPost = vod(deleteUrl);
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"cid\":\""+cid+"\"}",Consts.UTF_8);
        httpPost.setEntity(params);
		return responseData(httpPost,params);
	}
	/**
	 * 创建频道
	 * @param name 频道名称（最大长度64个字符，只支持中文、字母、数字和下划线）
	 * @param type 频道类型 ( 0 : rtmp, 1 : hls, 2 : http)
	 * @return ret:data
	 * cid	String	频道ID，32位字符串;ctime	Long	创建频道的时间戳;name	String	频道名称;pushUrl	String	推流地址;
	 * httpPullUrl	String	http拉流地址;hlsPullUrl	String	hls拉流地址;rtmpPullUrl	String	rtmp拉流地址;
	 * code	int	状态码;msg	String	错误信息
	 */
	public static String createChannel(String name,int type){
		HttpPost httpPost = vod(createUrl);
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"name\":\""+name+"\", \"type\":"+type+"}",Consts.UTF_8);
        httpPost.setEntity(params);
		return responseData(httpPost,params);
	}
	/**
	 * 网易视频云data
	 * @param url 请求地址
	 */
	public static HttpPost vod(String url){
        //CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		String appKey = PropertiesNtes.getAppKey();
		String appSecret = PropertiesNtes.getAppSecret();
		String nonce =  "1";
		String curTime = String.valueOf((new Date()).getTime() / 1000L);
		String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        // 设置请求的header
		httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
		return httpPost;
	}
	/**
	 * test
	 */
	public static String responseData(HttpPost httpPost,StringEntity params){
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 执行请求
        httpPost.setEntity(params);
        //HttpResponse response = httpClient.execute(httpPost);
        CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			//打印执行结果
			String entityUtils = EntityUtils.toString(entity, "utf-8");
			//System.out.println("--entityUtils-----"+entityUtils);
			//EntityUtils.consume(entity);
			return entityUtils;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * test
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static String vodTest(){
        CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("https://vcloud.163.com/app/channel/create");
		String appKey = PropertiesNtes.getAppKey();
		String appSecret = PropertiesNtes.getAppSecret();
		String nonce =  "1";
		String curTime = String.valueOf((new Date()).getTime() / 1000L);
		String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        // 设置请求的header
		httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            // 设置请求的参数
            StringEntity params = new StringEntity("{\"name\":\"netease_vcloud01\", \"type\":0}",Consts.UTF_8);
            // 执行请求
            httpPost.setEntity(params);
            //HttpResponse response = httpClient.execute(httpPost);
            CloseableHttpResponse response = null;
			try {
				response = httpClient.execute(httpPost);
				HttpEntity entity = response.getEntity();
				//打印执行结果
				String entityUtils = EntityUtils.toString(entity, "utf-8");
				//System.out.println("--entityUtils-----"+entityUtils);
				return entityUtils;
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					response.close();
					httpClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
	}
}
